#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>

int main(int argc, char **argv){
  int npart, i;
  char dummy[1024];
  float x, y, z;

  if ( strcmp(argv[0], "-h" ) == 0 ){
    printf("Usage: gettype <in-file (xyz)> <int type> <to char type>"); 
    exit(EXIT_SUCCESS);
  }

  if (argc != 4 ) 
    assert("Incorrect number of arguments");

  FILE *fin = fopen(argv[1], "r");
  if ( fin == NULL )
    assert("Couldn't open input file");

  int itype = atoi(argv[2]);
  char ctype = argv[3][0];
 
  fscanf(fin, "%d\n", &npart);
  fgets(dummy, 1024, fin);

  // Get number of this type
  int counter = 0;
  for ( int n=0; n<npart; n++){
    fscanf(fin, "%d", &i);
    if ( i==itype ) counter ++;
    fgets(dummy, 1024, fin);  
  }

  // Write to file
  FILE *fout = fopen("gettype.xyz", "w");
  if ( fout == NULL )
    assert("Couldn't open output file");

  fprintf(fout, "%d\n", counter);
  fprintf(fout, "Dummy text \n");
  
  rewind(fin);
  fscanf(fin, "%d\n", &npart);
  fgets(dummy, 1024, fin);
  
  for ( int n=0; n<npart; n++){
    fscanf(fin, "%d %f %f %f", &i, &x, &y, &z);
    if ( i==itype ){
      fprintf(fout, "%c %f %f %f\n", ctype, x, y, z);
    }
    fgets(dummy, 1024, fin);
  }

  fclose(fin); fclose(fout);

  return 0;
}
